﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Wpftest.ControlFile
{
    /// <summary>
    /// AttachControl.xaml 的交互逻辑
    /// </summary>
    /// 
    //声明附加事件变量并注册；通过静态方法添加或移除事件；引发附加事件
    public partial class AttachControl : UserControl
    {
        public AttachControl()
        {
            InitializeComponent();
        }

        //protected override void OnPreviewMouseLeftButtonDown(MouseButtonEventArgs e)
        //{
        //    base.OnPreviewMouseLeftButtonDown(e);
        //    RoutedEventArgs arg = new RoutedEventArgs(MyAttachEvent, this);
        //    RaiseEvent(arg);
        //}

        public static readonly RoutedEvent MyAttachEvent = EventManager.RegisterRoutedEvent("MyAttached", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(AttachControl));

        public static void AddMyAttachEventHandler(DependencyObject dp, RoutedEventHandler handler)
        {
            UIElement element = dp as UIElement;
            if (element != null)
            {
                element.AddHandler(MyAttachEvent,handler);
            }
        }
        public static void RemoveMyAttachEventHandler(DependencyObject dp, RoutedEventHandler handler)
        {
            UIElement element = dp as UIElement;
            if (element != null)
            {
                element.RemoveHandler(MyAttachEvent, handler);
            }
        }

        private void StackPanel_Click(object sender, RoutedEventArgs e)
        {
            var button = e.OriginalSource as Button;
            if (button != null)
            {
                MessageBox.Show(button.Content.ToString());
            }
        }
    }
}
